<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件下载管理器</title>
    <link rel="stylesheet" href="https://unpkg.com/layui@2.8.18/dist/css/layui.css">
    <style>
        .download-form .layui-form-item {
            margin-bottom: 20px;
        }
        .path-input-group {
            display: flex;
            align-items: center;
        }
        .path-input-group .layui-input {
            flex: 1;
            margin-right: 10px;
        }
        .path-select-btn {
            flex-shrink: 0;
        }
    </style>
</head>
<body>
    <div style="padding: 20px;">
        <button type="button" class="layui-btn" id="downloadBtn">下载</button>
    </div>

    <script src="https://unpkg.com/layui@2.8.18/dist/layui.js"></script>
    <script>
        /**
         * 文件下载管理器类
         */
        class FileDownloadManager {
            constructor() {
                this.layui = layui;
                this.layer = layui.layer;
                this.form = layui.form;
                this.element = layui.element;
                
                // 默认配置
                this.config = {
                    remoteIp: '',
                    remotePath: '',
                    localIp: '127.0.0.1',
                    localPath: '',
                    transferMode: 'scp' // scp 或 server
                };
                
                this.init();
            }
            
            /**
             * 初始化
             */
            init() {
                this.bindEvents();
            }
            
            /**
             * 绑定事件
             */
            bindEvents() {
                // 可以在外部调用 showDownloadDialog 方法
            }
            
            /**
             * 生成表单HTML
             */
            generateFormHTML() {
                return `
                    <form class="layui-form download-form" lay-filter="downloadForm" style="padding: 20px;">
                        <!-- 传输模式选择 -->
                        <div class="layui-form-item">
                            <label class="layui-form-label">传输模式</label>
                            <div class="layui-input-block">
                                <input type="radio" name="transferMode" value="scp" title="scp直传" ${this.config.transferMode === 'scp' ? 'checked' : ''}>
                                <input type="radio" name="transferMode" value="server" title="服务器中转" ${this.config.transferMode === 'server' ? 'checked' : ''}>
                            </div>
                        </div>
                        
                        <!-- 远程主机IP -->
                        <div class="layui-form-item">
                            <label class="layui-form-label">远程主机IP</label>
                            <div class="layui-input-block">
                                <input type="text" name="remoteIp" placeholder="请输入远程主机IP" 
                                       autocomplete="off" class="layui-input" value="${this.config.remoteIp}" readonly>
                            </div>
                        </div>
                        
                        <!-- 远程文件路径 -->
                        <div class="layui-form-item">
                            <label class="layui-form-label">远程文件路径</label>
                            <div class="layui-input-block">
                                <input type="text" name="remotePath" placeholder="请输入待下载的文件路径" 
                                       autocomplete="off" class="layui-input" value="${this.config.remotePath}">
                            </div>
                        </div>
                        
                        <!-- 本地主机IP -->
                        <div class="layui-form-item">
                            <label class="layui-form-label">本地主机IP</label>
                            <div class="layui-input-block">
                                <input type="text" name="localIp" placeholder="请输入本地主机IP" 
                                       autocomplete="off" class="layui-input" value="${this.config.localIp}">
                            </div>
                        </div>
                        
                        <!-- 本地接收路径 -->
                        <div class="layui-form-item">
                            <label class="layui-form-label">本地接收路径</label>
                            <div class="layui-input-block">
                                <div class="path-input-group">
                                    <input type="text" name="localPath" placeholder="请输入或选择本地接收路径" 
                                           autocomplete="off" class="layui-input" value="${this.config.localPath}">
                                    <button type="button" class="layui-btn layui-btn-primary layui-btn-sm path-select-btn" 
                                            lay-filter="selectPath">选择路径</button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 操作按钮 -->
                        <div class="layui-form-item" style="text-align: center; margin-top: 30px;">
                            <button type="button" class="layui-btn" lay-submit lay-filter="startDownload">开始下载</button>
                            <button type="button" class="layui-btn layui-btn-primary" id="cancelDownload">取消</button>
                        </div>
                    </form>
                `;
            }
            
            /**
             * 显示下载对话框
             */
            showDownloadDialog(options = {}) {
                // 更新配置
                Object.assign(this.config, options);
                
                const content = this.generateFormHTML();
                
                const index = this.layer.open({
                    type: 1,
                    title: '文件下载设置',
                    area: ['500px', 'auto'],
                    content: content,
                    success: (layero, index) => {
                        this.setupFormEvents(layero, index);
                        this.form.render(); // 重新渲染表单
                    }
                });
                
                return index;
            }
            
            /**
             * 设置表单事件
             */
            setupFormEvents(layero, layerIndex) {
                // 路径选择按钮事件
                layero.find('.path-select-btn').on('click', () => {
                    this.showPathSelector(layero);
                });
                
                // 取消按钮事件
                layero.find('#cancelDownload').on('click', () => {
                    this.layer.close(layerIndex);
                });
                
                // 表单提交事件
                this.form.on('submit(startDownload)', (data) => {
                    this.handleDownload(data.field, layerIndex);
                    return false;
                });
                
                // 单选框变化事件
                this.form.on('radio(transferMode)', (data) => {
                    console.log('传输模式切换为:', data.value);
                    this.config.transferMode = data.value;
                });
            }
            
            /**
             * 显示路径选择器
             */
            showPathSelector(parentLayero) {
                // 模拟路径选择器（实际项目中可能需要与后端交互）
                const commonPaths = [
                    '/home/user/Downloads',
                    '/tmp',
                    '/var/tmp',
                    'D:\\Downloads',
                    'C:\\Users\\用户\\Downloads'
                ];
                
                let pathOptions = '';
                commonPaths.forEach(path => {
                    pathOptions += `<div style="padding: 10px; border-bottom: 1px solid #eee; cursor: pointer;" 
                                    class="path-option" data-path="${path}">${path}</div>`;
                });
                
                this.layer.open({
                    type: 1,
                    title: '选择路径',
                    area: ['400px', '300px'],
                    content: `
                        <div style="padding: 10px;">
                            <div style="margin-bottom: 10px;">
                                <input type="text" placeholder="或直接输入路径" class="layui-input" id="customPath">
                            </div>
                            <div style="max-height: 200px; overflow-y: auto; border: 1px solid #eee;">
                                ${pathOptions}
                            </div>
                            <div style="text-align: center; margin-top: 15px;">
                                <button type="button" class="layui-btn layui-btn-sm" id="confirmPath">确定</button>
                                <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="cancelPath">取消</button>
                            </div>
                        </div>
                    `,
                    success: (pathLayero, pathIndex) => {
                        // 路径选项点击事件
                        pathLayero.find('.path-option').on('click', function() {
                            const selectedPath = $(this).data('path');
                            pathLayero.find('#customPath').val(selectedPath);
                            pathLayero.find('.path-option').removeClass('layui-bg-gray');
                            $(this).addClass('layui-bg-gray');
                        });
                        
                        // 确定按钮事件
                        pathLayero.find('#confirmPath').on('click', () => {
                            const selectedPath = pathLayero.find('#customPath').val();
                            if (selectedPath) {
                                parentLayero.find('input[name="localPath"]').val(selectedPath);
                                this.config.localPath = selectedPath;
                            }
                            this.layer.close(pathIndex);
                        });
                        
                        // 取消按钮事件
                        pathLayero.find('#cancelPath').on('click', () => {
                            this.layer.close(pathIndex);
                        });
                    }
                });
            }
            
            /**
             * 处理下载请求
             */
            handleDownload(formData, layerIndex) {
                // 表单验证
                if (!formData.remoteIp) {
                    this.layer.msg('请输入远程主机IP', {icon: 2});
                    return;
                }
                
                if (!formData.remotePath) {
                    this.layer.msg('请输入远程文件路径', {icon: 2});
                    return;
                }
                
                if (!formData.localIp) {
                    this.layer.msg('请输入本地主机IP', {icon: 2});
                    return;
                }
                
                if (!formData.localPath) {
                    this.layer.msg('请输入本地接收路径', {icon: 2});
                    return;
                }
                
                // 更新配置
                Object.assign(this.config, formData);
                
                console.log('下载配置:', this.config);
                
                // 显示加载层
                const loadIndex = this.layer.load(2, {shade: [0.3, '#000']});
                
                // 模拟下载过程
                setTimeout(() => {
                    this.layer.close(loadIndex);
                    this.layer.close(layerIndex);
                    
                    // 这里调用实际的下载逻辑
                    this.performDownload(this.config);
                }, 2000);
            }
            
            /**
             * 执行下载（需要根据实际情况实现）
             */
            performDownload(config) {
                console.log('开始下载文件...');
                console.log('配置信息:', config);
                
                // 这里可以发送ajax请求到后端
                /*
                $.ajax({
                    url: '/api/download',
                    method: 'POST',
                    data: config,
                    success: (result) => {
                        this.layer.msg('下载任务已启动', {icon: 1});
                        // 可以显示下载进度等
                    },
                    error: (error) => {
                        this.layer.msg('下载失败: ' + error.message, {icon: 2});
                    }
                });
                */
                
                this.layer.msg('下载任务已启动', {icon: 1});
            }
            
            /**
             * 更新配置
             */
            updateConfig(newConfig) {
                Object.assign(this.config, newConfig);
            }
            
            /**
             * 获取当前配置
             */
            getConfig() {
                return { ...this.config };
            }
        }
        
        // 使用示例
        layui.use(['layer', 'form', 'element'], function() {
            // 创建下载管理器实例
            const downloadManager = new FileDownloadManager();
            
            // 绑定下载按钮事件
            document.getElementById('downloadBtn').addEventListener('click', function() {
                // 可以传入初始配置
                downloadManager.showDownloadDialog({
                    remoteIp: '192.168.1.100',
                    remotePath: '/home/user/data.txt',
                    localPath: '/home/local/downloads'
                });
            });
        });
    </script>
</body>
</html>